package com.jier.service.impl;

import com.jier.common.util.StringUtil;
import com.jier.dao.SystemRolePermissionDao;
import com.jier.entities.SystemPermission;
import com.jier.entities.SystemRolePermission;
import com.jier.service.ISystemRolePermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * 系统角色权限业务实现类
 *
 * @author jie_r
 * @date 2018/03/23
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class SystemRolePermissionServiceImpl extends BaseServiceImpl<SystemRolePermissionDao, SystemRolePermission> implements ISystemRolePermissionService {
    @Override
    public void updateSystemRolePermission(Integer roleId, List<Integer> permissionIds) throws Exception {
        // 删除权限
        deleteSystemRolePermission(roleId);
        // 添加权限
        if(StringUtil.isNotEmptyList(permissionIds)) {
            for (Integer permissionId : permissionIds) {
                SystemRolePermission systemRolePermission = new SystemRolePermission();
                systemRolePermission.setSystemRoleId(roleId);
                systemRolePermission.setSystemPermissionId(permissionId);
                systemRolePermission.setUpdateDate(new Date());
                systemRolePermission.setCreateDate(new Date());
                save(systemRolePermission);
            }
        }
    }

    @Override
    public boolean getRolePermissionByCode(Integer roleId, String permissionCode) throws Exception {
        List<SystemPermission> systemPermissions = mapper.getRolePermissionByCode(roleId, permissionCode);
        if (StringUtil.isEmptyList(systemPermissions)) {
            return false;
        }
        return true;
    }

    public void deleteSystemRolePermission(Integer roleId) throws Exception {
        Example example = getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("systemRoleId", roleId);
        deleteByExample(example);
    }

}
